<template>
	<view class="bind-house-page">

		<!-- 导航栏 -->
        <view class="bind-house-page-navbar" :style="{backgroundImage: `url(${getImg('votion_form_headr_back_image.svg')})`}" >
		<u-navbar
		:titleStyle ="{color: navTitleColor}"
        :leftIconColor="navTitleColor"  
       :bgColor="navColor"
       title="绑定房屋" 
       :placeholder="true" 
     
        :autoBack="true">
		</u-navbar>
        <view class="content-wrapper">
			<!-- 未选择房屋状态 -->
			<NotSelectCom v-if="selectedHouses.length === 0" @select-house="openHouseModal" />

			<!-- 已选择房屋状态 -->
			<SelectCom v-else v-model="selectedHouses" @add-house="openHouseModal" />

			<!-- 信息提示 -->
			<view class="info-section ">
				<view class="info-item">
                    <view class="info-item-icon">
                        <u-image src="/static/info-icon.svg" width="24rpx" height="24rpx"/>
                    </view>
					<!-- <image class="icon" src="/static/info-icon.svg"></image> -->
					<text>产权证明资料仅用于本小程序业主身份核验，个人隐私信息将会脱敏处理，请放心操作。</text>
				</view>
				<view class="info-item warning">
                    <u-image src="/static/warning.svg" width="18px" height="18px"/>
					<text style="font-size: 12px;" >特别提醒：切勿冒用、伪造他人信息，否则将依法追究法律责任。</text>
				</view>
			</view>
		</view>
		</view>

		

		<!-- 底部提交按钮 -->
		<view class="bottom-bar">
			<view class="submit-btn" :disabled="selectedHouses.length === 0"
				@click="submit">提交</view>
		</view>

		<!-- 房屋选择弹窗 -->
		<ChooseHouseModel v-model="showModal" @confirm="handleHouseConfirm"
		 :communityId="communityId" />
	</view>
</template>

<script>
	import ChooseHouseModel from '@/components/ChooseHouseModel/index.vue';
	import NotSelectCom from './components/NotSelectCom.vue';
	import SelectCom from './components/SelectCom.vue';
	import { addApply ,getAreaQuery} from '@/api';
    import {mapState} from 'vuex';
	import ls from '@/util/ls'
	export default {
		components: {
			ChooseHouseModel,
			NotSelectCom,
			SelectCom
		},
		data() {
			return {
				selectedHouses: [
               
                ],
				showModal: false,
				scrollTop: 0,
				hooseHouselist:[],
				jumstatus:"back",
				source:""
				//  communityId:2
				// navTitleColor: '#ffffff',
				// navColor: 'rgba(0,0,0,0)',
			};
		},
		computed: {
		   ...mapState("community",[
				"communityId"
			]),
			navColor() {
			return this.scrollTop === 0 ? 'rgba(0,0,0,0)' : `rgba(255,255,255,${this.scrollTop/100})`
			},
			navTitleColor() {
			return this.scrollTop === 0 ? '#ffffff' : '#333333';
			}
		},
		onLoad(options) {
			this.init(options)
		},
	  onPageScroll(e){
			this.scrollTop = e.scrollTop
			},
		methods: {
			init(options){
			if(options.statue){
            this.jumstatus=options.statue
			}
			if(options.source){
				this.source=options.source
			}
			},
			openHouseModal() {
				this.showModal = true;
			},
			handleHouseConfirm(confirmedRooms) {
				
				// confirmedRooms 结构为 [{ building, unit, room, buildingId, unitId, roomId }]
				const existingKeys = new Set(this.selectedHouses.map(h => h.key));
				const newRooms = confirmedRooms.filter(item => {
					const key = `${item.building}-${item.unit}-${item.room}`;
					return !existingKeys.has(key);
				}).map(item => ({
					key: `${item.building}-${item.unit}-${item.room}`,
					areaName: item.areaName,
					building: item.building,
					unit: item.unit,
					room: item.room,
					buildingId: item.buildingId,
					unitId: item.unitId,
					roomId: item.roomId,
					fileList: [],
					area: ''
				}));
				this.selectedHouses = [...this.selectedHouses, ...newRooms];
			
			},
			submit() {
				
				if (this.selectedHouses.length === 0) {
					uni.showToast({
						title: '请先选择房屋',
						icon: 'none'
					});
					return;
				}
				for (const house of this.selectedHouses) {
					const houseLabel = `${house.building || ''}${house.unit || ''}${house.room || ''}`;
					if (!house.fileList || house.fileList.length === 0) {
						uni.showToast({
							title: `请为 ${houseLabel} 上传产权证明`,
							icon: 'none'
						});
						return;
					}
					if(!house.name){
						uni.showToast({
							title: `请为 ${houseLabel} 输入姓名`,
							icon: 'none'
						});
						return;
					
					// if (!house.area) {
					// 	uni.showToast({
					// 		title: `请为 ${houseLabel} 输入房屋面积`,
					// 		icon: 'none'
					// 	});
					
						
					}
					if(!house.identity){
						uni.showToast({
							title: `请为 ${houseLabel} 选择业主身份`,
							icon: 'none'
						});
						return
					}
				}
				let useinfo=ls.get('user')
				
				let wxUserId=useinfo.wxUser
			
					const applyPromises = this.selectedHouses.map(row => {
					
					return addApply({
						houseRoomId: row.roomId,
						liveUserId: wxUserId.wxUserId.toString(),
						wxUserId: 1,
						phone: wxUserId.mobile,
						name: row.name,
						auditStatus: 1,
						 communityId:this.communityId ,
						identity:row.identity,
                        images:row.fileList.join(',')
					});
				});
				Promise.all(applyPromises)
				.then(res => {
					
					let datas=res[0]
				
					if(datas.code==200){
					uni.showToast({
						title: "提交成功",
						icon: 'success'
					});
					if(this.source=="related"){
						uni.navigateBack()
						return;
					}
					let timer=setTimeout(() => {
						uni.redirectTo({
							url: `/pages/applyForActivation/index?status=1&jumstatus=${this.jumstatus}`
						});
						clearTimeout(timer)
					}, 800);
					}else{
						uni.showToast({
							title: datas.msg,
							icon: 'none'
						});
					}
				})
				.catch(err => {
				
				});
                // let row=this.selectedHouses[0]
				// addApply({houseRoomId:row.roomId,
				// liveUserId:wxUserId.wxUserId,wxUserId:1,
				// phone:wxUserId.mobile,name:wxUserId.nickName,auditStatus:1})
				// .then(res => {
				//   uni.navigateTo({
				// 	url: '/pages/bindhouse/success'
				//   })
				// })
				// .catch(err => {
			
				// })
				
				
			}
		}
	}
</script>

<style lang="scss" >
	page {
        width: 100%;
        height: 100%;
		background-color: #F3F6FC;
	}

	.bind-house-page {
        height: 100%;
        width: 100%;
        background-color: #F3F6FC;
		padding-bottom: 180rpx;
        &-navbar{
            width:100%;
            height: 474rpx;
            // background: linear-gradient( 180deg, rgba(61,109,217,0.8) 0%, #F3F6FC 100%);
			background-size: cover;
        }
	}

	.u-nav-slot {
		display: flex;
		align-items: center;
		margin-right: 30rpx;
	}

	.nav-circle {
		width: 44rpx;
		height: 44rpx;
		border: 1px solid #333;
		border-radius: 50%;
		margin-left: 20rpx;
	}

	.content-wrapper {
		padding: 24rpx 30rpx;
	}

	.card {
		background: linear-gradient( 180deg, #D8EAFF 0%, #F8FAFD 25%,#ffffff 100%);
        box-shadow: inset 0rpx 2rpx 0rpx 0rpx #FFFFFF, 0rpx 5rpx 14rpx 0rpx rgba(169,194,209,0.1);
        border-radius: 18rpx; 
	}

	.selected-state-card {
		padding: 40rpx;
		
		.selected-house-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			background: #F7F8FA;
			border-radius: 8rpx;
			padding: 24rpx;
			margin-bottom: 24rpx;

			.house-info {
				font-size: 28rpx;
				color: #333;
			}
		}

		.add-more-btn {
			height: 80rpx;
			background: #F0F5FF;
			border-radius: 8rpx;
			color: #4D7FFF;
			font-size: 30rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.add-more-btn-text {
				margin-left: 8rpx;
			}
		}
	}

	.info-section {
		margin-top: 40rpx;
		padding: 0 20rpx;
        padding-bottom: 200rpx;
         
		.info-item {
			display: flex;
			align-items: flex-start;
			font-size: 24rpx;
			color: #666666;
			line-height: 1.6;
            text{
                margin-left: 14rpx;
            }

			&-icon {
				width: 28rpx;
				height: 28rpx;
				position: relative;
                top: 8rpx;
			}

			&.warning {
				font-weight: 400;
                font-size: 24rpx;
                color: #F9901B;
                position: relative;
                left: -5.5rpx;
			}

			&:last-child {
				margin-top: 20rpx;
			}
		}
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx 50rpx;
		padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		background-color: #ffffff;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);

		.submit-btn {
			height: 88rpx;
			background: #3B75FA;
            border-radius: 12rpx;
			color: #FFFFFF;
			font-size: 30rpx;
            font-weight: 500;
			border: none;
            display: flex;
            align-items: center;
            justify-content: center;
			
			&::after {
				border: none;
			}
		}
	}
</style>
